<?php

namespace App\Http\Controllers\Api\Goods;

use App\Http\Controllers\Api\Goods\GoodsLogic;
use App\Http\Controllers\Controller;
use App\Libs\Strategy\Context;
use App\Models\Goods\Cates;
use App\Models\Goods\Goods;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class GoodsController extends Controller
{
    private $goods;

    public function __construct(){
        $this->goods = new Context(new Goods());
    }

    public function index(Request $request)
    {
        $cates = GoodsLogic::getCate();
        $goods = $this->goods->display($request->limit,function($query) use($request){
            if($request->keyword)
            {
                $query->where('goods_name','like','%'.$request->keyword.'%')->orWhere('goods_num','like','%'.$request->keyword.'%');
            }
            if($request->cate)
            {
               $id = Str::after($request->cate,'/');
               $query->where('goods_cate_id',$id);
            }
            if($request->is_show)
            {
               $query->where('is_show',$request->is_show);
            }
        });
        return $goods;
    }


    public function store(Request $request)
    {
        $this->validate($request,[
            'goods_img' => 'required',
        ],[
            'goods_img.required' => '商品图片不能为空',
        ]);
        if($this->goods->create($request->only('goods_name','goods_img','goods_price','goods_original_price','goods_sales','sort','is_show','is_home','goods_market_price','goods_postage','stock') + ['goods_desc'=>$request->desc,'goods_num'=>Str::uuid()->getTimeLow()])){
             return $this->success(['message'=>'添加成功']);
        };
        return $this->error('添加失败');
    }

    public function update(Request $request,$id)
    {
        $this->validate($request,[
            'goods_img' => 'required',
        ],[
            'goods_img.required' => '商品图片不能为空',
        ]);
        if($this->goods->update($id,$request->only('goods_name','goods_img','goods_price','goods_original_price','goods_desc','goods_sales','sort','is_show','is_home','goods_market_price','goods_postage','stock'))){
             return $this->success(['message'=>'编辑成功']);
        };
        return $this->error('编辑失败');
    }

    public function destroy($id)
    {
        if($this->goods->find($id)->delete($id))
        {
            return $this->success(['message'=>'删除成功']);
        }
        return $this->error('删除失败');
    }
}
